<template>
  <div class="box-card">
    <el-form inline>
      <el-form-item label="班级">
        <el-select
          v-model="query.classId"
          clearable
          @change="handleQueryChange"
        >
          <el-option
            v-for="c in classList"
            :key="c.id"
            :label="c.className"
            :value="c.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="课程">
        <el-select
          v-model="query.courseId"
          clearable
          @change="handleQueryChange"
        >
          <el-option
            v-for="c in courseList"
            :key="c.id"
            :label="c.courseName"
            :value="c.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学期">
        <el-select
          v-model="query.semesterId"
          clearable
          @change="handleQueryChange"
        >
          <el-option
            v-for="s in semesterList"
            :key="s.id"
            :label="s.year + '第' + s.term + '学期'"
            :value="s.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="成绩状态">
        <el-select
          v-model="query.scored"
          clearable
          @change="handleQueryChange"
          placeholder="全部"
        >
          <el-option label="全部" :value="null" />
          <el-option label="已录入" :value="1" />
          <el-option label="未录入" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否有效">
        <el-select
          v-model="query.isValid"
          clearable
          @change="handleQueryChange"
          placeholder="全部"
        >
          <el-option label="全部" :value="null" />
          <el-option label="有效" :value="1" />
          <el-option label="无效" :value="0" />
        </el-select>
      </el-form-item>
    </el-form>

    <el-table
      :data="studentPage.records"
      border
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column
        prop="className"
        label="班级"
        align="center"
        header-align="center"
      />
      <el-table-column
        prop="courseName"
        label="课程"
        align="center"
        header-align="center"
      />
      <el-table-column
        prop="studentAccount"
        label="学号"
        align="center"
        header-align="center"
      />
      <el-table-column
        prop="studentName"
        label="姓名"
        align="center"
        header-align="center"
      />
      <el-table-column label="成绩" align="center" header-align="center">
        <template slot-scope="scope">
          <template v-if="editRow === scope.row">
            <el-input-number
              v-model="editForm.score"
              :min="0"
              :max="100"
              size="mini"
            />
          </template>
          <template v-else>
            <template
              v-if="scope.row.score !== null && scope.row.score !== undefined"
            >
              <el-tag
                :type="getScoreTagType(scope.row.score)"
                disable-transitions
              >
                {{ scope.row.score }}
              </el-tag>
            </template>
            <template v-else>
              <el-tag size="mini" type="info"> 未录入 </el-tag>
            </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="成绩描述" align="center" header-align="center">
        <template slot-scope="scope">
          <template v-if="editRow === scope.row">
            <el-input
              v-model="editForm.description"
              size="mini"
              ref="descInput"
              :placeholder="
                editForm.isValid === 0 ? '必填：如作弊、缺考等' : ''
              "
              :style="editForm.isValid === 0 ? 'border:1px solid #f56c6c;' : ''"
            />
          </template>
          <template v-else>
            {{ scope.row.description || "无" }}
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="semester"
        label="学期"
        align="center"
        header-align="center"
      />
      <el-table-column label="是否有效" align="center" header-align="center">
        <template slot-scope="scope">
          <template v-if="editRow === scope.row">
            <el-select
              v-model="editForm.isValid"
              size="mini"
              style="width: 80px"
            >
              <el-option :value="1" label="有效" />
              <el-option :value="0" label="无效" />
            </el-select>
          </template>
          <template v-else>
            <template
              v-if="scope.row.score !== null && scope.row.score !== undefined"
            >
              <el-tag :type="scope.row.isValid ? 'success' : 'danger'">
                {{ scope.row.isValid ? "有效" : "无效" }}
              </el-tag>
            </template>
            <template v-else>
              <span></span>
            </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="120"
        align="center"
        header-align="center"
      >
        <template slot-scope="scope">
          <template v-if="editRow === scope.row">
            <el-button type="primary" size="mini" @click="saveEdit(scope.row)"
              >保存</el-button
            >
            <el-button size="mini" @click="cancelEdit">取消</el-button>
          </template>
          <template v-else>
            <el-button type="text" size="mini" @click="startEdit(scope.row)">{{
              scope.row.score !== null && scope.row.score !== undefined
                ? "修改"
                : "录入"
            }}</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px; text-align: center">
      <el-pagination
        background
        :current-page="query.pageNo"
        :page-size="query.pageSize"
        :total="studentPage.total"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 30, 50, 100]"
      />
    </div>
  </div>
</template>

<script>
import { getClassByCurrentUser } from "@/api/class";
import { getCourseByTeacherId } from "@/api/course";
import { getAllSemester } from "@/api/semester";
import { getStudentScoresByTeacher, saveOrUpdateScore } from "@/api/score";

export default {
  data() {
    return {
      classList: [],
      courseList: [],
      semesterList: [],
      query: {
        classId: null,
        courseId: null,
        semesterId: null,
        pageNo: 1,
        pageSize: 10,
        scored: null,
        isValid: null,
      },
      studentPage: {
        total: 0,
        records: [],
      },
      editRow: null,
      editForm: {
        id: null,
        score: null,
        description: "",
        semesterId: null,
        courseId: null,
        isValid: 0,
      },
    };
  },
  methods: {
    startEdit(row) {
      this.editRow = row;
      this.editForm = {
        score: row.score,
        description: row.description || "",
        isValid:
          row.score === null || row.score === undefined
            ? 1
            : Number(row.isValid), // 没有成绩时默认为有效
      };
    },
    cancelEdit() {
      this.editRow = null;
      this.editForm = { score: null, description: "", isValid: 1 };
    },
    async saveEdit(row) {
      if (
        this.editForm.score === null ||
        this.editForm.score === undefined ||
        isNaN(this.editForm.score) ||
        this.editForm.score < 0 ||
        this.editForm.score > 100
      ) {
        this.$message.warning("成绩必须在0-100之间");
        return;
      }
      if (this.editForm.isValid === 0 && !this.editForm.description.trim()) {
        this.$message.warning("成绩无效时必须填写成绩描述（如作弊、缺考等）");
        return;
      }

      // 构建参数
      const addOrUpdateParams = {
        id: row.id,
        semesterId: row.semesterId,
        studentId: row.studentId,
        courseId: row.courseId,
        isValid: this.editForm.isValid,
        score: this.editForm.score,
        description: this.editForm.description,
      };
      let res = await saveOrUpdateScore(addOrUpdateParams);
      if (res.code == 200) {
        this.$message.success(res.data);
      } else {
        this.$message.error(res.msg);
      }

      this.fetchStudentPage();
    },

    // 获取班级数据
    async fetchClassList() {
      const res = await getClassByCurrentUser();
      this.classList = res.data || [];
    },

    // 根据教师id获取课程数据
    async fetchCourseList() {
      const res = await getCourseByTeacherId();
      this.courseList = res.data || [];
    },

    // 获取学期数据
    async fetchSemesterList() {
      const res = await getAllSemester();
      this.semesterList = res.data || [];
      // 自动选择当前学期
      let { id } = this.getCurrentTerm(this.semesterList, new Date());
      this.query.semesterId = id;
      // 学期选好后再查
      this.fetchStudentPage();
    },

    //获取老师教授班级的成绩
    async fetchStudentPage() {
      const res = await getStudentScoresByTeacher(this.query);
      this.studentPage.records = res.data.records || [];
      this.studentPage.total = res.data.total;
    },

    handleQueryChange() {
      this.query.pageNo = 1; // 确保使用pageNo而不是page
      this.fetchStudentPage();
    },

    handlePageChange(page) {
      this.query.pageNo = page;
      this.fetchStudentPage();
    },
    handleSizeChange(size) {
      this.query.pageSize = size;
      this.query.pageNo = 1; // 更改每页数量时重置为第一页
      this.fetchStudentPage();
    },

    // 获取当前学期
    getCurrentTerm(semesters, currentDateStr) {
      const currentDate = new Date(currentDateStr || new Date());
      const sortedSemesters = semesters
        .map((s) => ({
          ...s,
          startDateObj: new Date(s.startDate),
          endDateObj: new Date(s.endDate),
        }))
        .sort((a, b) => a.startDateObj - b.startDateObj);
      for (let sem of sortedSemesters) {
        if (currentDate >= sem.startDateObj && currentDate <= sem.endDateObj) {
          return sem;
        }
      }
      let previousSemester = null;
      for (let sem of sortedSemesters) {
        if (currentDate >= sem.endDateObj) {
          previousSemester = sem;
        } else {
          break;
        }
      }
      return previousSemester;
    },

    // 成绩颜色区分
    getScoreTagType(score) {
      if (score < 60) {
        return "danger"; // 红色
      } else if (score >= 90) {
        return "primary"; // 蓝色，优秀
      } else {
        return "success"; // 绿色
      }
    },
  },
  mounted() {
    Promise.all([
      this.fetchClassList(),
      this.fetchCourseList(),
      this.fetchSemesterList(),
    ]);
  },
  watch: {
    "editForm.isValid"(val) {
      if (val === 0) {
        this.$nextTick(() => {
          this.$refs.descInput && this.$refs.descInput.focus();
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.box-card {
  margin: 20px;
}
</style>
